package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.OrderTo;
import com.atguigu.common.to.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberVo;
import com.atguigu.gulimall.order.config.AlipayTemplate;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WareFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> submitVoThreadLocal=new ThreadLocal<>();

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    PaymentInfoService paymentInfoService;


    @Transactional()
    public void a(){
        //使用AspectJ动态代理获取本类代理对象，解决Spring本类事务互调失效问题
        OrderServiceImpl o = (OrderServiceImpl) AopContext.currentProxy();
        o.b();
        o.c();
    }
    @Transactional
    public void b(){

    }
    @Transactional
    public void c(){

    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询订单确认页的VO信息
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo=new OrderConfirmVo();
        MemberVo memberVo = LoginUserInterceptor.threadLocal.get();
        //原来的请求属性
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            //1、远程调用会员服务，获取收货地址列表
            //每个异步线程共享原来的请求属性
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddressByMemberId(memberVo.getId());
            confirmVo.setAddress(address);
        }, executor);
        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //2、远程调用购物车服务获取购物项
            //每个异步线程共享原来的请求属性
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> cartItems = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(cartItems);
        }, executor).thenRunAsync(()->{
            List<Long> skuIds = confirmVo.getItems().stream().map(item -> {
                return item.getSkuId();
            }).collect(Collectors.toList());
            R skusHasStock = wareFeignService.getSkusHasStock(skuIds);
            List<SkuHasStockVo> data = skusHasStock.getData(new TypeReference<List<SkuHasStockVo>>() {
            });
            Map<Long, Boolean> stocks = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
            confirmVo.setStocks(stocks);
        },executor);
        //3、用户积分信息
        Integer integration = memberVo.getIntegration();
        confirmVo.setIntegration(integration);
        //4、其他数据自动计算

        // TODO 5、防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberVo.getId(),token,30L, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);
        CompletableFuture.allOf(addressFuture,cartFuture).get();
        return confirmVo;
    }

    /**
     * 创建订单、验令牌、验价格、锁库存
     * @GlobalTransactional  是seata的全局事务管理，配置好后，只需要标注该注解在全局事务中（即最大的事务），就能保证分布式事务一致性问题
     * @param submitVo
     * @return
     */
    //@GlobalTransactional  //seata的全局事务注解
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo submitVo) {
        submitVoThreadLocal.set(submitVo);
        SubmitOrderResponseVo responseVo=new SubmitOrderResponseVo();
        MemberVo memberVo = LoginUserInterceptor.threadLocal.get();
        responseVo.setCode(0);
        //令牌删除脚本，返回1则代表删除成功，返回0则代表失败
        String script="if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        //前端传来的token
        String orderToken = submitVo.getOrderToken();
        //原子验证令牌和删除令牌
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId()), orderToken);
        if(result == 0){
            //验证失败
            responseVo.setCode(1);
            return responseVo;
        }else {
            //验证成功
            //创建订单、验令牌、验价格、锁库存
            //1、创建订单
            OrderCreateTo order = createOrder();
            //2、验价
            //订单应付金额
            BigDecimal payAmount = order.getOrder().getPayAmount();
            //页面提交的金额
            BigDecimal payPrice = submitVo.getPayPrice();
            if(Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01){
                //3、验证价成功,保存订单信息和订单项信息
                saveOrder(order);
                //4、锁定库存（关联订单号、所有订单项（skuId、skuName、数量等）），库存锁定失败时回滚
                WareSkuLockVo lockVo=new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> locks = order.getItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);
                //远程锁库存，很重要
                R r = wareFeignService.orderLockStock(lockVo);
                if(r.getCode() == 0){
                    //锁定成功
                    responseVo.setOrder(order.getOrder());
                    // TODO 远程调用扣减积
                    // int a=10/0;
                    //订单创建成功，发送消息给MQ,将订单作为消息发送出去
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                    return responseVo;
                }else {
                    //锁定失败
                    String msg= (String) r.get("msg");
                    throw new NoStockException(msg);
                }
            }else {
                responseVo.setCode(2);
                return responseVo;
            }
        }
    }

    /**
     * 获取订单状态
     * @param orderSn
     * @return
     */
    @Override
    public OrderEntity getOrderStatus(String orderSn) {
        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return orderEntity;
    }

    /**
     * 订单超时未支付，进行关单操作
     * @param orderEntity
     */
    @Override
    public void closeOrder(OrderEntity orderEntity) {
        OrderEntity byId = this.getById(orderEntity.getId());
        if(byId.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()){
            //如果超时订单还是代付款状态，则进行关单
            OrderEntity update = new OrderEntity();
            update.setId(byId.getId());
            //取消状态
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo=new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            //订单取消之后，发送消息给库存锁定，让其释放库存
            rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
        }
    }

    /**
     * 设置订单信息
     * @param orderSn
     * @return
     */
    @Override
    public PayVo payOrder(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderEntity = this.getOrderStatus(orderSn);
        BigDecimal bigDecimal = orderEntity.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        //设置总额
        payVo.setTotal_amount(bigDecimal.toString());
        List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        if(itemEntities!=null && itemEntities.size()>0){
            OrderItemEntity itemEntity = itemEntities.get(0);
            //设置标题和备注
            payVo.setSubject(itemEntity.getSkuName());
            payVo.setBody(itemEntity.getSkuAttrsVals());
        }
        //设置商户订单号
        payVo.setOut_trade_no(orderEntity.getOrderSn());
        return payVo;
    }

    /**
     * 查询用户订单列表，且包含订单项
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageWithItems(Map<String, Object> params) {
        //当前用户信息
        MemberVo memberVo = LoginUserInterceptor.threadLocal.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberVo.getId()).orderByDesc("id")
        );
        List<OrderEntity> orderEntities = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItems(itemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(orderEntities);
        return new PageUtils(page);
    }

    /**
     * 处理订单支付结果
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1、保存交易流水
        PaymentInfoEntity infoEntity=new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(infoEntity);
        if(vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")){
            //订单支付成功，修改订单状态
            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    /**
     * 创建秒杀单的详细信息
     * @param seckillOrderTo
     */
    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrderTo) {
        //TODO 保存秒杀订单信息
        OrderEntity orderEntity=new OrderEntity();
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal realPay = seckillOrderTo.getSeckillPrice().multiply(new BigDecimal(seckillOrderTo.getNum()));
        orderEntity.setPayAmount(realPay);
        orderEntity.setOrderSn(seckillOrderTo.getOrderSn());
        this.save(orderEntity);

        //TODO 保存订单项信息，需远程调用订单服务
        OrderItemEntity itemEntity=new OrderItemEntity();
        itemEntity.setOrderSn(seckillOrderTo.getOrderSn());
        itemEntity.setRealAmount(realPay);
        itemEntity.setSkuQuantity(seckillOrderTo.getNum());
        orderItemService.save(itemEntity);
    }

    /**
     * 保存订单信息和订单项信息
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        //1、保存订单信息
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.baseMapper.insert(orderEntity);
        //2、保存订单项信息
        List<OrderItemEntity> items = order.getItems();
        orderItemService.saveBatch(items);
    }

    private OrderCreateTo createOrder(){
        OrderCreateTo createTo = new OrderCreateTo();
        //生成订单号
        String orderSn = IdWorker.getTimeId();
        //1、构建订单
        OrderEntity orderEntity = buildOrder(orderSn);
        //2、获取所有订单项信息
        List<OrderItemEntity> orderItems = buildOrderItems(orderSn);
        //3、计算价格,积分等相关
        computePrice(orderEntity,orderItems);
        createTo.setOrder(orderEntity);
        createTo.setItems(orderItems);
        return createTo;
    }

    /**
     * 计算订单价格
     * @param orderEntity
     * @param orderItems
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItems) {
        //订单总额，所有订单项真实金额的叠加
        BigDecimal total=new BigDecimal("0.0");
        BigDecimal promotion=new BigDecimal("0.0");
        BigDecimal coupon=new BigDecimal("0.0");
        BigDecimal integration=new BigDecimal("0.0");
        BigDecimal giftIntegration=new BigDecimal("0.0");
        BigDecimal giftGrowth=new BigDecimal("0.0");
        for (OrderItemEntity orderItem : orderItems) {
            //当前订单项的真实金额
            total=total.add(orderItem.getRealAmount());
            //订单项的促销金额
            promotion=promotion.add(orderItem.getPromotionAmount());
            //订单项的积分金额
            coupon=coupon.add(orderItem.getCouponAmount());
            //订单项的优惠券金额
            integration=integration.add(orderItem.getIntegrationAmount());
            //积分
            giftIntegration= giftIntegration.add(new BigDecimal(orderItem.getGiftIntegration().toString()));
            //成长值
            giftGrowth= giftGrowth.add(new BigDecimal(orderItem.getGiftGrowth().toString()));
        }
        //设置订单总额
        orderEntity.setTotalAmount(total);
        //设置订单应付总额是订单总额加上运费总额
        orderEntity.setPayAmount(orderEntity.getTotalAmount().add(orderEntity.getFreightAmount()));
        //设置促销总额
        orderEntity.setPromotionAmount(promotion);
        //设置优惠券总额
        orderEntity.setCouponAmount(coupon);
        //设置积分总额
        orderEntity.setIntegrationAmount(integration);
        //设置积分
        orderEntity.setIntegration(giftIntegration.intValue());
        //设置成长值
        orderEntity.setGrowth(giftGrowth.intValue());
        orderEntity.setConfirmStatus(0);
        orderEntity.setDeleteStatus(0);
    }

    /**
     * 构建订单
     * @param orderSn
     * @return
     */
    private OrderEntity buildOrder(String orderSn) {
        MemberVo memberVo = LoginUserInterceptor.threadLocal.get();
        //设置订单号
        OrderEntity orderEntity=new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        //设置会员id
        orderEntity.setMemberId(memberVo.getId());
        OrderSubmitVo orderSubmitVo = submitVoThreadLocal.get();
        R fare = wareFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareVo = fare.getData(new TypeReference<FareVo>() {
        });
        //设置运费
        orderEntity.setFreightAmount(fareVo.getFare());
        //设置收货人地址信息
        MemberAddressVo address = fareVo.getAddress();
        orderEntity.setReceiverCity(address.getCity());
        orderEntity.setReceiverDetailAddress(address.getDetailAddress());
        orderEntity.setReceiverName(address.getName());
        orderEntity.setReceiverPhone(address.getPhone());
        orderEntity.setReceiverProvince(address.getProvince());
        orderEntity.setReceiverPostCode(address.getPostCode());
        orderEntity.setReceiverRegion(address.getRegion());
        //设置订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        //自动收货时间
        orderEntity.setAutoConfirmDay(7);
        return orderEntity;
    }

    /**
     * 创建所有的订单项
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if(currentUserCartItems != null && currentUserCartItems.size()>0){
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                //设置订单号
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /**
     * 构建单个订单项
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity=new OrderItemEntity();
        //1、订单信息，订单号，在构建所有订单项时设置
        //2、spu信息
        R r = productFeignService.getSpuInfoBySkuId(cartItem.getSkuId());
        SpuInfoVo spuInfoVo = r.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        itemEntity.setSpuId(spuInfoVo.getId());
        itemEntity.setSpuName(spuInfoVo.getSpuName());
        itemEntity.setCategoryId(spuInfoVo.getCatalogId());
        //3、sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        itemEntity.setSkuQuantity(cartItem.getCount());
        String skuAttrStr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttrs(), ";");
        itemEntity.setSkuAttrsVals(skuAttrStr);
        //4、优惠信息【不做】
        //5、积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //6、订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0.0"));
        itemEntity.setCouponAmount(new BigDecimal("0.0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0.0"));
        //原来的价格
        BigDecimal origin = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        //优惠后的价格
        itemEntity.setRealAmount(
                origin.subtract(itemEntity.getPromotionAmount().
                subtract(itemEntity.getCouponAmount().
                subtract(itemEntity.getIntegrationAmount()))));
        return itemEntity;
    }

}